package com.example.VolunteerBank.service.impl;

import com.example.VolunteerBank.mapper.ArticleMapper;
import com.example.VolunteerBank.pojo.Article;
import com.example.VolunteerBank.pojo.PageBean;
import com.example.VolunteerBank.service.ArticleService;
import com.example.VolunteerBank.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
@Slf4j
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    //新增文章
    @Override
    public void add(Article article) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId);
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.add(article);
    }

    //更新文章
    @Override
    public void update(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.update(article);
    }

    //获取文章详情
    @Override
    public Article queryById(Integer id) {
        return articleMapper.queryById(id);
    }

    //删除文章
    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }

    //分页查询文章列表
    @Override
    public PageBean<Article> page(Integer pageNum, Integer pageSize, String categoryId, String state) {
        PageBean<Article> pageBean = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Page<Article> page = articleMapper.page(userId, categoryId, state);
        pageBean.setItems(page.getResult());
        pageBean.setTotal(page.getTotal());
        return pageBean;
    }
}
